Telegram Group & Telegram Channel
Inverts a dictionary with non-unique hashable values.

👉Create a collections.defaultdict with list as the default value for each key.

👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

👉Use dict() to convert the collections.defaultdict to a regular dictionary.

CODE:

from collections import defaultdict

def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)

Example:

ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)

Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

Share and Support
@Python_Codes



tg-me.com/python_codes/220
Create:
Last Update:

Inverts a dictionary with non-unique hashable values.

👉Create a collections.defaultdict with list as the default value for each key.

👉Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().

👉Use dict() to convert the collections.defaultdict to a regular dictionary.

CODE:

from collections import defaultdict

def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)

Example:

ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages)

Output: { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

Share and Support
@Python_Codes

BY Python Codes


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/python_codes/220

View MORE
Open in Telegram


Python Codes Telegram | DID YOU KNOW?

Date: |

The STAR Market, as is implied by the name, is heavily geared toward smaller innovative tech companies, in particular those engaged in strategically important fields, such as biopharmaceuticals, 5G technology, semiconductors, and new energy. The STAR Market currently has 340 listed securities. The STAR Market is seen as important for China’s high-tech and emerging industries, providing a space for smaller companies to raise capital in China. This is especially significant for technology companies that may be viewed with suspicion on overseas stock exchanges.

The S&P 500 slumped 1.8% on Monday and Tuesday, thanks to China Evergrande, the Chinese property company that looks like it is ready to default on its more-than $300 billion in debt. Cries of the next Lehman Brothers—or maybe the next Silverado?—echoed through the canyons of Wall Street as investors prepared for the worst.

Python Codes from ms


Telegram Python Codes
FROM USA